package com.ev.hr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ev.apis.model.DsResultResponse;
import com.ev.framework.utils.DateFormatUtil;
import com.ev.framework.utils.R;
import com.ev.framework.utils.StringUtils;
import com.ev.hr.dao.SalaryArchivesDao;
import com.ev.hr.dao.SalaryChangeDao;
import com.ev.hr.domain.SalaryArchivesDO;
import com.ev.hr.domain.SalaryChangeDO;
import com.ev.hr.service.SalaryArchivesService;
import com.ev.hr.vo.SalaryArchivesPageParam;
import com.ev.system.service.RoleService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class SalaryArchivesServiceImpl implements SalaryArchivesService {
	@Autowired
	private SalaryChangeDao salaryChangeDao;
	@Autowired
	private SalaryArchivesDao salaryArchivesDao;
	@Autowired
	private RoleService roleService;


	@Override
	public SalaryArchivesDO get(Long id){
		return salaryArchivesDao.get(id);
	}
	
	@Override
	public List<SalaryArchivesDO> list(Map<String, Object> map){
		return salaryArchivesDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return salaryArchivesDao.count(map);
	}
	
	@Override
	public int save(SalaryArchivesDO salaryArchives){
		return salaryArchivesDao.save(salaryArchives);
	}
	
	@Override
	public int update(SalaryArchivesDO salaryArchives){
		return salaryArchivesDao.update(salaryArchives);
	}

	@Override
	public int updateAll(SalaryArchivesDO salaryArchives){
		return salaryArchivesDao.updateAll(salaryArchives);
	}
	
	@Override
	public int remove(Long id){
		return salaryArchivesDao.remove(id);
	}
	
	@Override
	public int batchRemove(Long[] ids){
		return salaryArchivesDao.batchRemove(ids);
	}

	@Override
	public R saveAndVerify(SalaryArchivesDO saveParam){
		if(saveParam.getId()!=null){
			return salaryArchivesDao.update(saveParam)>0?R.ok():R.error();
		}
		return salaryArchivesDao.save(saveParam)>0?R.ok():R.error();
	}

	@Override
	public Map<String, Object> getById(Long id) {
		Map<String, Object> detail = this.salaryArchivesDao.getById(id);
		if (detail != null) {
			List<Map<String, Object>> changeList = Lists.newArrayList();
			String salaryProjectJson = detail.get("salaryProjectJson").toString();
			JSONArray jsonArray = JSON.parseArray(salaryProjectJson);
			Map<String, Object> firstMap = Maps.newHashMap();
			jsonArray.forEach(jo -> {
				JSONObject jsonObject = (JSONObject) jo;
				firstMap.put(jsonObject.getString("property"), jsonObject.getString("amount"));
			});
			firstMap.put("effectiveDate", detail.get("effectiveDate"));
			firstMap.put("postFixedLevel", detail.getOrDefault("postFixedLevel", ""));
			changeList.add(firstMap);

			Map<String, Object> param = Maps.newHashMap();
			Object employeeId = detail.get("employeeId");
			param.put("employeeId", employeeId);
			List<SalaryChangeDO> salaryChangeDOList = salaryChangeDao.list(param);

			Map<String, Object> lastMap;
			for (SalaryChangeDO changeDO : salaryChangeDOList) {
				String salaryProjectJs = changeDO.getSalaryProjectJson();
				JSONArray jsonList = JSON.parseArray(salaryProjectJs);
				lastMap = Maps.newHashMap();
				lastMap.put("effectiveDate", DateFormatUtil.getFormateDate(changeDO.getEffectiveDate()));
				lastMap.put("changeRemark", changeDO.getChangeRemark());
				lastMap.put("changeReason", changeDO.getChangeReason());
				lastMap.put("postFixedLevel", changeDO.getPostFixedLevel() == null ? "" : changeDO.getPostFixedLevel());
				for (Object o : jsonList) {
					JSONObject jsonObject = (JSONObject) o;
					lastMap.put(jsonObject.getString("property"), jsonObject.getString("amount"));
				}
				changeList.add(lastMap);
			}
			changeList.sort(Comparator.comparing(e -> e.get("effectiveDate").toString()));
			changeList.forEach(e -> e.put("isNow", false));
			// 若最后一个调薪记录小于或等于当前日期则为现在的薪资
			Date now = new Date();

			for (int i = changeList.size() - 1; i >= 0; i--) {
				Map<String, Object> map = changeList.get(i);
				Date effectiveDate = DateFormatUtil.getDateByParttern(map.get("effectiveDate").toString(), DateFormatUtil.DATE_PATTERN_YMD);
				Calendar effectiveDates = Calendar.getInstance();
				assert effectiveDate != null;
				effectiveDates.setTime(effectiveDate);
				effectiveDates.set(Calendar.DAY_OF_MONTH, 1);
				if (now.after(effectiveDates.getTime())) {
					map.put("isNow", true);
					break;
				}

			}

			detail.put("salaryChangeList", changeList);
			Map<String, Object> result = Maps.newHashMap();

			result.put("data", detail);
			return R.ok(result);
		}
		return R.error();
	}

	@Override
	public Map<String, Object> pageList(SalaryArchivesPageParam pageParam) {
		Map<String,Object> result = Maps.newHashMap();
		pageParam.setEmployeeName(StringUtils.sqlLike(pageParam.getEmployeeName()));
		pageParam.setEmployeeCode(StringUtils.sqlLike(pageParam.getEmployeeCode()));

		JSONObject o = (JSONObject) JSONObject.toJSON(pageParam);
		o.putAll(roleService.getDataPermission(3));

		List<Map<String, Object>> data = salaryArchivesDao.pageList(o);
		if (data.size() > 0) {
			data.forEach(e->{
				String salaryProjectJson = e.get("salaryProjectJson").toString();
				JSONArray jsonArray = JSON.parseArray(salaryProjectJson);
				jsonArray.forEach(jo->{
					JSONObject jsonObject = (JSONObject) jo;
					e.put(jsonObject.getString("property"),jsonObject.getString("amount"));
				});
			});

			int total = salaryArchivesDao.pageCount(o);
			result.put("data", new DsResultResponse(pageParam.getPageno(),pageParam.getPagesize(),total,data));
		}
		return R.ok(result);
	}

	@Override
	public void batchInsert(List<SalaryArchivesDO> salaryArchivesDOList) {
		salaryArchivesDao.batchInsert(salaryArchivesDOList);
	}

}
